import 'package:ai_data_capture/req/api/ConfigApi.dart';
import 'package:ai_data_capture/req/exp.dart';
import 'package:ai_data_capture/util/JsonUtil.dart';
import 'package:ai_data_capture/util/toast_util.dart';
import 'package:ai_data_capture/widget/dialog.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';

import 'state.dart';

class ProgramListLogic extends GetxController {
  final ProgramListState state = ProgramListState();
  @override
  void onInit() {
    super.onInit();
    init();
  }

  Future<void> init() async {
    state.fList.addAll(await ConfigApi.getFunctions());
  }

  Future<void> runFunction(String bean) async {
    try {
      await ConfigApi.run_single_step(bean);
      showToast("已经开始运行");
    } on ApiException catch (e) {
      showToast(e.message);
    } on DioException catch (e) {
      showToast(e.message ?? "");
    }
  }

  Future<void> editSingleConfig(String bean) async {
    try {
      var c = await ConfigApi.getConfig(bean);
      if (c == null) {
        showToast("获取配置失败");
        return;
      }
      String? txt = await showEditDialog(JsonUtil.unzipJson(c));
      if (txt != null) {
        submitConfig(bean, txt);
      }
    } catch (e) {
      if (e is ApiException) {
        showToast(e.message);
      } else {
        print("获取配置失败");
      }
    }
  }

  Future<void> submitConfig(type, txt) async {
    try {
      await ConfigApi.setConfig(type, txt);
      showToast("提交成功");
    } catch (e) {
      showToast("提交失败:$e");
    }
  }
}
